/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.star.spring.rocketmq.listener;

import java.nio.ByteBuffer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;

import com.star.spring.rocketmq.annotation.OnMessage;

import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PushConsumerConsumerService {

    @OnMessage(consumerGroup = "normal-group", topic = "topic-normal")
    public ConsumeResult handleNormalMessage(MessageView messageView) {
        log.info("Normal message received: {}", messageView);
        decodeMessage(messageView);

        return ConsumeResult.SUCCESS;
    }


    @OnMessage(consumerGroup = "fifo-group", topic = "topic-fifo", tag = "*")
    public ConsumeResult handleFifoMessage(MessageView messageView) {
        log.info("FIFO message received: {}", messageView);
        decodeMessage(messageView);

        return ConsumeResult.SUCCESS;
    }

    @OnMessage(consumerGroup = "delay-group", topic = "topic-delay")
    public ConsumeResult handleDelayMessage(MessageView messageView) {
        log.info("Delay message received: {}", messageView);
        decodeMessage(messageView);

        return ConsumeResult.SUCCESS;
    }

    @OnMessage(consumerGroup = "trans-group", topic = "topic-trans")
    public ConsumeResult handleTransMessage(MessageView messageView) {
        log.info("Receive transactional message check, message={}", messageView);
        decodeMessage(messageView);
        return ConsumeResult.SUCCESS;
    }

    private void decodeMessage(MessageView messageView) {
        ByteBuffer body = messageView.getBody();
        byte[] bytes = new byte[body.remaining()];
        body.get(bytes);
        String message = new String(bytes);
        log.info("Message is like : {}", message);
    }
}
